package cn.monkey.chat.server.connect.config;

import cn.monkey.chat.server.connect.chat.netty.NettyChatExchangeManager;
import cn.monkey.chat.server.connect.chat.protocol.http.HttpUserSessionInboundHandler;
import cn.monkey.chat.server.connect.chat.protocol.http.ws.TextChatMessageInboundHandler;
import cn.monkey.chat.server.connect.chat.protocol.http.ws.TextChatMessageOutboundHandler;
import cn.monkey.chat.server.connect.chat.session.UserSessionRepository;
import cn.monkey.io.transport.netty.server.codec.protocol.ServerProtocolRouterFunction;
import cn.monkey.io.transport.netty.server.codec.protocol.tcp.http.ws.WebsocketServerProtocolRouterFunction;
import cn.monkey.io.transport.netty.utils.ChannelHandlerUtils;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class WebsocketConfig {
    @Bean
    ServerProtocolRouterFunction websocketRouterFunction(UserSessionRepository userSessionRepository,
                                                         NettyChatExchangeManager nettyChatExchangeManager) {
        return new WebsocketServerProtocolRouterFunction(WebSocketServerProtocolConfig.newBuilder().checkStartsWith(true).websocketPath("/").build(), channel -> {
            ChannelPipeline pipeline = channel.pipeline();
            pipeline.addAfter(ChannelHandlerUtils.normalizeName(HttpObjectAggregator.class),
                            ChannelHandlerUtils.normalizeName(HttpUserSessionInboundHandler.class),
                            new HttpUserSessionInboundHandler(userSessionRepository))
                    .addLast(new TextChatMessageInboundHandler(nettyChatExchangeManager))
                    .addLast(new TextChatMessageOutboundHandler());
        });
    }
}
